using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Http;
using QW.Core.File;
using QW.Core.Helper;

namespace QW.UEditor.Handlers
{
    /// <summary>
    /// 文件列表处理器
    /// </summary>
    public class ListFileHandler : BaseHandler
    {
        enum ResultState
        {
            Success,
            InvalidParam,
            AuthorizError,
            IOError,
            PathNotFound
        }

        private int Start;
        private int Size;
        private int Total;
        private ResultState State;
        private String PathToList;
        private String[] FileList;
        private String[] SearchExtensions;
        /// <summary>
        /// .ctor
        /// </summary>
        /// <param name="context"></param>
        /// <param name="pathToList"></param>
        /// <param name="searchExtensions"></param>
        public ListFileHandler(HttpContext context, string pathToList, string[] searchExtensions)
            : base(context)
        {
            this.SearchExtensions = searchExtensions.Select(x => x.ToLower()).ToArray();
            this.PathToList = pathToList;
        }
        /// <summary>
        /// 处理过程
        /// </summary>
        public override void Process()
        {
            try
            {
                Start = String.IsNullOrEmpty(Request.Query["start"]) ? 0 : Convert.ToInt32(Request.Query["start"]);
                Size = String.IsNullOrEmpty(Request.Query["size"]) ? Config.GetInt("imageManagerListSize") : Convert.ToInt32(Request.Query["size"]);
            }
            catch (FormatException)
            {
                State = ResultState.InvalidParam;
                WriteResult();
                return;
            }
            var buildingList = new List<String>();
            try
            {
                var localPath = IOHelper.PathCombine(Config.SaveFileRootPath, PathToList);
                buildingList.AddRange(GetFolderFiles(localPath, localPath)
                    .Where(x => SearchExtensions.Contains(Path.GetExtension(x).ToLower()))
                    .Select(x => IOHelper.PathCombine(PathToList, x)));
                Total = buildingList.Count;
                FileList = buildingList.OrderBy(x => x).Skip(Start).Take(Size).ToArray();
            }
            catch (UnauthorizedAccessException)
            {
                State = ResultState.AuthorizError;
            }
            catch (DirectoryNotFoundException)
            {
                State = ResultState.PathNotFound;
            }
            catch (IOException)
            {
                State = ResultState.IOError;
            }
            finally
            {
                WriteResult();
            }
        }

        public List<string> GetFolderFiles(string path, string basepath)
        {
            List<string> result = new List<string>();
            //result = Directory.GetFiles(path, "*", SearchOption.AllDirectories).Select(x => x.Substring(basepath.Length).Replace("\\", "/")).ToList();

            #region 使用QW.Core的文件处理器
            result = FileHandler.GetFolderFiles(path, true).Select(x => x.Substring(basepath.Length).Replace("\\", "/")).ToList();
            //处理子目录
            var subdirs = FileHandler.GetFolderSubFolder(path,isFullName:true);
            foreach (var item in subdirs)
            {
                result.AddRange(GetFolderFiles(item, basepath));
            }
            #endregion

            return result;
        }

        private void WriteResult()
        {
            WriteJson(new
            {
                state = GetStateString(),
                list = FileList == null ? null : FileList.Select(x => new { url = x }),
                start = Start,
                size = Size,
                total = Total
            });
        }

        private string GetStateString()
        {
            switch (State)
            {
                case ResultState.Success:
                    return "SUCCESS";
                case ResultState.InvalidParam:
                    return "参数不正确";
                case ResultState.PathNotFound:
                    return "路径不存在";
                case ResultState.AuthorizError:
                    return "文件系统权限不足";
                case ResultState.IOError:
                    return "文件系统读取错误";
            }
            return "未知错误";
        }
    }
}